<template>
  <div class="equip-management">
    <!-- 页面标题和操作按钮 -->
    <div class="header">
      <h2>设备管理</h2>
      <div class="actions">
        <el-button type="primary" @click="refreshData">刷新数据</el-button>
        <el-button type="success" @click="handleAdd">添加设备</el-button>
      </div>
    </div>

    <!-- 添加/编辑设备对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      :title="isEditing ? '编辑设备' : '添加设备'" 
      width="500px"
      :before-close="handleEditDialogClose"
    >
      <el-form 
        ref="editFormRef" 
        :model="editForm" 
        :rules="editFormRules" 
        label-width="100px"
      >
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入设备名称" />
        </el-form-item>
        
        <!-- 添加模式和编辑模式显示不同的字段 -->
        <template v-if="!isEditing">
          <!-- 添加模式：只需要设备名称和描述 -->
          <el-form-item label="设备描述" prop="description">
            <el-input 
              v-model="editForm.description" 
              type="textarea" 
              :rows="4" 
              placeholder="请输入设备描述（可选）"
            />
          </el-form-item>
        </template>
        
        <template v-else>
          <!-- 编辑模式：显示完整的字段 -->
          <el-form-item label="登记人" prop="recorder">
            <el-input v-model="editForm.recorder" placeholder="请输入登记人" />
          </el-form-item>
          <el-form-item label="登记时间" prop="recordTime">
            <el-date-picker
              v-model="editForm.recordTime"
              type="datetime"
              placeholder="选择登记时间"
              style="width: 100%;"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="设备状态" prop="status">
            <el-select v-model="editForm.status" placeholder="请选择设备状态" style="width: 100%">
              <el-option label="空闲" value="空闲" />
              <el-option label="使用中" value="使用中" />
              <el-option label="维修中" value="维修中" />
              <el-option label="报废" value="报废" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备描述" prop="description">
            <el-input 
              v-model="editForm.description" 
              type="textarea" 
              :rows="4" 
              placeholder="请输入设备描述"
            />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditDialogClose">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleEditConfirm" 
            :loading="editLoading"
          >
            {{ isEditing ? '保存' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备列表表格 -->
    <el-table 
      ref="multipleTableRef" 
      :data="tableData" 
      row-key="id" 
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="设备ID" width="100" />
      <el-table-column prop="name" label="设备名称" width="200" />
      <el-table-column prop="recorder" label="登记人" width="120" />
      <el-table-column prop="recordTime" label="登记时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.recordTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="设备状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="设备描述" min-width="200" />
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="{ row }">
          <el-button 
            link 
            type="primary" 
            size="small" 
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button 
            link 
            type="danger" 
            size="small" 
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { TableInstance, FormInstance, FormRules } from 'element-plus'
import axios from 'axios'

// 设备接口类型定义
interface Equipment {
  id: number
  name: string
  recorder: string
  recordTime: string
  status: string
  description: string
  updateTime: string
}

// 响应式数据
const multipleTableRef = ref<TableInstance>()
const tableData = ref<Equipment[]>([])
const loading = ref(false)
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editLoading = ref(false)
const isEditing = ref(false)

const editForm = reactive<Equipment>({
  id: 0,
  name: '',
  recorder: '',
  recordTime: '',
  status: '',
  description: '',
  updateTime: ''
})

// 动态表单验证规则
const editFormRules = reactive<FormRules<Equipment>>({
  name: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 50, message: '设备名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  // 编辑模式下的额外验证规则
  recorder: [
    { required: true, message: '请输入登记人', trigger: 'blur' }
  ],
  recordTime: [
    { required: true, message: '请选择登记时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择设备状态', trigger: 'change' }
  ]
})

// 状态映射
const statusTextToValue: Record<string, number> = {
  '空闲': 1,
  '使用中': 2,
  '维修中': 3,
  '报废': 4
}
const statusValueToText: Record<number, string> = {
  1: '空闲',
  2: '使用中',
  3: '维修中',
  4: '报废'
}

// 编辑对话框关闭
const handleEditDialogClose = () => {
  editDialogVisible.value = false
  editFormRef.value?.resetFields()
  isEditing.value = false
}

// 添加设备 - 使用新的接口格式
const handleAddEquipment = async () => {
  try {
    // 获取当前登录用户的ID
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('请先登录')
      return
    }

    // 按照接口文档的参数格式
    const params = {
      name: editForm.name,
      userId: parseInt(userId), // 使用当前登录用户的ID
      description: editForm.description || '' // 可选字段，如果为空则传空字符串
    }

    console.log('添加设备参数:', params)

    const response = await axios.post('http://localhost:8080/api/v1/admin/enroll', params)
    
    if (response.data.code === 200) {
      ElMessage.success('设备添加成功')
      editDialogVisible.value = false
      await getEquipmentList() // 刷新设备列表
    } else {
      ElMessage.error(response.data.message || '设备添加失败')
    }
  } catch (error: any) {
    console.error('添加设备失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      ElMessage.error(error.response.data.message || '设备添加失败')
    } else {
      ElMessage.error('网络请求失败，请稍后重试')
    }
  }
}

// 更新设备
const handleUpdateEquipment = async () => {
  try {
    // 按照接口文档要求的参数格式（驼峰命名）
    const params = {
      id: editForm.id,
      name: editForm.name,
      recorder: editForm.recorder,
      recordTime: editForm.recordTime, // 使用驼峰命名
      status: typeof editForm.status === 'string' ? statusTextToValue[editForm.status] : editForm.status,
      description: editForm.description,
      updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ') // 自动设置更新时间
    }

    console.log('更新设备参数:', params)

    const response = await axios.post('http://localhost:8080/api/v1/admin/UpdateEquipStatus', params)
    
    if (response.data.code === 200) {
      ElMessage.success('设备状态更新成功')
      editDialogVisible.value = false
      await getEquipmentList() // 刷新设备列表
    } else {
      ElMessage.error(response.data.message || '设备状态更新失败')
    }
  } catch (error: any) {
    console.error('更新设备失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      ElMessage.error(error.response.data.message || '设备状态更新失败')
    } else {
      ElMessage.error('网络请求失败，请稍后重试')
    }
  }
}
// 编辑确认
const handleEditConfirm = async () => {
  if (!editFormRef.value) return
  
  try {
    // 动态验证规则：添加模式只验证名称，编辑模式验证所有字段
    const fieldsToValidate = isEditing.value 
      ? ['name', 'recorder', 'recordTime', 'status'] 
      : ['name']
    
    await editFormRef.value.validateField(fieldsToValidate)
    editLoading.value = true

    if (isEditing.value) {
      // 更新设备
      await handleUpdateEquipment()
    } else {
      // 添加设备
      await handleAddEquipment()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.warning('请完善必填信息')
  } finally {
    editLoading.value = false
  }
}

// 获取设备列表
const getEquipmentList = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:8080/api/v1/admin/equStatus')
    if (response.data.code === 200) {
      // 字段名转换，下划线转驼峰
      tableData.value = response.data.data.map((item: any) => ({
        id: item.id,
        name: item.name,
        recorder: item.recorder,
        recordTime: item.record_time,
        status: item.status,
        description: item.description,
        updateTime: item.update_time
      }))
      console.log('设备列表:', tableData.value)
    } else {
      ElMessage.error(response.data.message || '获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('网络请求失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  getEquipmentList()
}

// 处理添加设备
const handleAdd = () => {
  // 设置为添加模式
  isEditing.value = false
  
  // 清空表单
  Object.assign(editForm, {
    id: 0,
    name: '',
    recorder: '',
    recordTime: '',
    status: '',
    description: '',
    updateTime: ''
  })
  
  editDialogVisible.value = true
  
  // 确保表单重置
  setTimeout(() => {
    editFormRef.value?.clearValidate()
  }, 0)
}

// 处理编辑设备
const handleEdit = (row: Equipment) => {
  // 设置为编辑模式
  isEditing.value = true
  
  // 填充表单数据
  Object.assign(editForm, {
    id: row.id,
    name: row.name,
    recorder: row.recorder,
    recordTime: row.recordTime,
    status: row.status,
    description: row.description,
    updateTime: row.updateTime
  })
  
  editDialogVisible.value = true
}

// 删除设备
const handleDelete = async (row: Equipment) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除设备 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 调用删除接口
    const response = await axios.post(`http://localhost:8080/api/v1/admin/delete/${row.id}`)
    if (response.data.code === 200) {
      ElMessage.success('设备删除成功')
      await getEquipmentList()
    } else {
      ElMessage.error(response.data.message || '设备删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除设备失败:', error)
      if (error.response) {
        ElMessage.error(error.response.data.message || '设备删除失败')
      } else {
        ElMessage.error('网络请求失败，请稍后重试')
      }
    }
  }
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 根据状态返回对应的标签类型
const getStatusTagType = (status: string) => {
  const statusTypeMap: Record<string, string> = {
    '空闲': '1',
    '使用': '2',
    '维修': '3',
    '报废': '4'
  }
  return statusTypeMap[status] || 'default'
}

// 处理选择变化
const multipleSelection = ref<Equipment[]>([])
const handleSelectionChange = (val: Equipment[]) => {
  multipleSelection.value = val
}

onMounted(() => {
  getEquipmentList()
})
</script>

<style scoped>
.equip-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.actions {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>